# -*- coding: utf-8 -*-
import sys
import time
import datetime
import os
import xlrd
import warnings
warnings.simplefilter("ignore", UserWarning)
sys.coinit_flags = 2

from erpauto import Erpauto
from ui import Ui_Form
from DYSHOP import DYSHOP

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

from PyQt5.QtWidgets import QApplication, QMainWindow,QFileDialog,QSplashScreen
from PyQt5.QtCore import QSettings, Qt, QThread, pyqtSignal,pyqtSlot, QPoint
from PyQt5 import QtGui,QtWidgets
from open_chrome import openchromedef


class Myapp(QtWidgets.QWidget, Ui_Form):
    def __init__(self):
        super(Myapp, self).__init__()

        # 设置窗口在最前方并且无边框
        self.setWindowFlags(Qt.WindowStaysOnTopHint|Qt.FramelessWindowHint)

        self.setupUi(self)
        self.toolButton.clicked.connect(self.read_file)
        self.toolButton_2.clicked.connect(self.read_file2)
        self.toolButton_3.clicked.connect(self.write_folder)
        self.pushButton_2.clicked.connect(self.dyauto)
        self.pushButton.clicked.connect(self.process1)
        self.pushButton_3.clicked.connect(self.auto)
        self.pushButton_4.clicked.connect(self.open_chrome)
        self.init_conf()

        # 设置窗口背景
        palette = QtGui.QPalette()
        pix = QtGui.QPixmap("./resource/background1.jpg")
        pix = pix.scaled(self.width(), self.height())
        palette.setBrush(QtGui.QPalette.Background, QtGui.QBrush(pix))
        self.setPalette(palette)
        # 设置应用图标
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("./resource/dy.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)

    def save_conf(self):
        """
        保存用户配置信息
        :return:
        """
        settings = QSettings('config.ini', QSettings.IniFormat)
        settings.setIniCodec("GB2312")  # 防止中文乱码
        settings.setValue('CHROMEDRIVER', self.lineEdit.text())
        settings.setValue('EXCEL_PATH', self.lineEdit_2.text())
        settings.setValue('WORK_PATH', self.lineEdit_3.text())
        settings.setValue('IMG_PATH', self.lineEdit_4.text())

    def init_conf(self):
        """
        初始化配置信息
        :return:
        """
        settings = QSettings('config.ini', QSettings.IniFormat)
        settings.setIniCodec("GB2312")  # 防止中文乱码
        work = settings.value("WORK_PATH")
        chrome_driver = settings.value("CHROMEDRIVER")
        excel_path = settings.value("EXCEL_PATH")
        img_path = settings.value("IMG_PATH")
        self.lineEdit.setText(chrome_driver)
        self.lineEdit_2.setText(excel_path)
        self.lineEdit_3.setText(work)
        self.lineEdit_4.setText(img_path)

    def read_file2(self):
        # 选取文件
        filename, filetype = QFileDialog.getOpenFileName(self, "选取文件", "E:/", "All Files(*.xlsx)")
        print(filename, filetype)
        self.lineEdit_2.setText(filename)

    def write_folder(self):
        # 选取文件夹
        foldername = QFileDialog.getExistingDirectory(self, "选择输出路径", "E:/")
        print(foldername)
        self.lineEdit_3.setText(foldername)

    def read_file(self):
        # 选取文件
        filename, filetype = QFileDialog.getOpenFileName(self, "选择可执行文件", "E:/", "All Files(*.exe)")
        print(filename, filetype)
        self.lineEdit.setText(filename)
        # self.printf(self.lineEdit.text())


    def process1(self):

        try:
            auto =self.autostatus
            # 移动窗口至右上角
            desktop = QApplication.desktop()
            self.move(desktop.width() - self.width(), 0)
            # 单击改变按钮样式
            self.pushButton.setText('Ongoing')
            self.pushButton.setStyleSheet("color: rgb(137, 221, 255);\n"
                                          "background-color: rgb(0,205,0,0.5);\n"
                                          "border-style:none;\n"
                                          "border:1px solid #3f3f3f; \n"
                                          "\n"
                                          "padding:5px;\n"
                                          "\n"
                                          "border-radius:8px;")
            self.pushButton.setEnabled(False)

            self.printf('开始执行erp自动准备数据')
            excel_path = self.lineEdit_2.text()
            work_path_ = self.lineEdit_3.text()
            work_path = work_path_.replace("/", "\\")
            mythread1 = Mythread1(excel_path, work_path)
            mythread1.erpauto.connect(self.printf)
            mythread1.erpbtnsignal.connect(self.erpbtn)
            # mythread1.erpbtnsignal.connect(self.dyauto)
            mythread1.erpbtnsignal.connect(self.open_chrome)
            mythread1.start()
            mythread1.exec()

        except AttributeError:
            # 移动窗口至右上角
            desktop = QApplication.desktop()
            self.move(desktop.width() - self.width(), 0)
            # 单击改变按钮样式
            self.pushButton.setText('Ongoing')
            self.pushButton.setStyleSheet("color: rgb(137, 221, 255);\n"
                                          "background-color: rgb(0,205,0,0.5);\n"
                                          "border-style:none;\n"
                                          "border:1px solid #3f3f3f; \n"
                                          "\n"
                                          "padding:5px;\n"
                                          "\n"
                                          "border-radius:8px;")
            self.pushButton.setEnabled(False)

            self.printf('开始执行erp自动准备数据')
            excel_path = self.lineEdit_2.text()
            work_path_ = self.lineEdit_3.text()
            work_path = work_path_.replace("/", "\\")
            mythread1 = Mythread1(excel_path, work_path)
            mythread1.erpauto.connect(self.printf)
            mythread1.erpbtnsignal.connect(self.erpbtn)
            mythread1.start()
            mythread1.exec()



    def erpbtn(self):

        self.pushButton.setStyleSheet("color: rgb(137, 221, 255);\n"
          "background-color: rgb(37, 121, 255,0.5);\n"
          "border-style:none;\n"
          "border:1px solid #3f3f3f; \n"
          "\n"
          "padding:5px;\n"
          "\n"
          "border-radius:8px;")
        self.pushButton.setEnabled(True)
        self.pushButton.setText('restart')

    def triggerdyauto(self):
        self.dyauto()


    # def dyauto(self):
    #
    #     self.printf('开始执行抖音小店自动上新')
    #
    #     chrome_options = Options()
    #     chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9999")
    #     # chrome_driver = r"C:\Users\mgxx\PycharmProjects\untitled7\autofill-core\chromedriver.exe"
    #     chrome_driver = self.lineEdit.text()
    #     self.printf('你的chromedriver路径为：{}'.format(chrome_driver))
    #     # chrome_driver = r"E:\chromedriver85.exe"
    #
    #     driver = webdriver.Chrome(chrome_driver, options=chrome_options)
    #     dyshop = DYSHOP(driver)
    #     dyshop.start()
    #     dyshop.login()
    #
    #     work_path_ = self.lineEdit_3.text()
    #     work_path = work_path_.replace("/", "\\")
    #     dict_path = os.path.join(work_path, 'goods_dict.txt')
    #
    #     with open(dict_path, 'r+') as f:
    #         goods_dict = eval(f.read())
    #         f.close()
    #     # goods_dict = {'MA032405-2': ['MA032405-2', '套装-毛衣', ['花色'], ['S', 'M', 'L', 'XL']],
    #     #               'MQ032254': ['MQ032254', '连衣裙', ['黑色', '天蓝色'], ['XS', 'S', 'M', 'L', 'XL']],
    #     #               'MA032551-1': ['MA032551-1', '套装-衬衫', ['白色'], ['XS', 'S', 'M', 'L', 'XL']]}
    #     for good in goods_dict:
    #         dyshop.create_goods(goods_dict[good])
    #         self.printf('{} 货号为:{}'.format(datetime.datetime.now(), good))
    #     self.printf('执行完毕')
    def dyauto(self):

        try:
            auto = self.autostatus
            # 移动窗口至右上角
            desktop = QApplication.desktop()
            self.move(desktop.width() - self.width(), 0)
            # 单击改变按钮样式
            self.pushButton_2.setText('Ongoing')
            self.pushButton_2.setStyleSheet("color: rgb(137, 221, 255);\n"
            "background-color: rgb(0,205,0,0.5);\n"
            "border-style:none;\n"
            "border:1px solid #3f3f3f; \n"
            "\n"
            "padding:5px;\n"
            "\n"
            "border-radius:8px;")
            self.pushButton_2.setEnabled(False)

            self.printf('开始进行网页填充')
            chrome_driver = self.lineEdit.text()
            work_path_ = self.lineEdit_3.text()
            work_path = work_path_.replace("/", "\\")
            mythread2 = Mythread2(chrome_driver,work_path)
            mythread2.chromesig.connect(self.printf)
            mythread2.dybtnsignal.connect(self.dybtn)
            mythread2.dybtnsignal.connect(self.autoover)
            mythread2.start()
            mythread2.exec()
        except AttributeError:
            # 移动窗口至右上角
            desktop = QApplication.desktop()
            self.move(desktop.width() - self.width(), 0)
            # 单击改变按钮样式
            self.pushButton_2.setText('Ongoing')
            self.pushButton_2.setStyleSheet("color: rgb(137, 221, 255);\n"
                                            "background-color: rgb(0,205,0,0.5);\n"
                                            "border-style:none;\n"
                                            "border:1px solid #3f3f3f; \n"
                                            "\n"
                                            "padding:5px;\n"
                                            "\n"
                                            "border-radius:8px;")
            self.pushButton_2.setEnabled(False)

            self.printf('开始进行网页填充')
            chrome_driver = self.lineEdit.text()
            work_path_ = self.lineEdit_3.text()
            work_path = work_path_.replace("/", "\\")
            mythread2 = Mythread2(chrome_driver, work_path)
            mythread2.chromesig.connect(self.printf)
            mythread2.dybtnsignal.connect(self.dybtn)
            mythread2.start()
            mythread2.exec()

    def autoover(self):
        self.printf('正在保存配置')
        self.save_conf()
        self.printf('保存成功')
        self.pushButton_3.setEnabled(True)
        self.pushButton_3.setText('执行\n完成')
        self.pushButton_3.setStyleSheet("color: rgb(137, 221, 255);\n"
        "background-color: rgb(37, 121, 255,0.5);\n"
        "border-style:none;\n"
        "border:1px solid #3f3f3f; \n"
        "\n"
        "padding:5px;\n"
        "min-height:20px;\n"
        "border-radius:25px;")





    def dybtn(self):
        self.printf('完成自动填充')
        print('网页上新完成')
        self.pushButton_2.setStyleSheet("color: rgb(137, 221, 255);\n"
          "background-color: rgb(37, 121, 255,0.5);\n"
          "border-style:none;\n"
          "border:1px solid #3f3f3f; \n"
          "\n"
          "padding:5px;\n"
          "\n"
          "border-radius:8px;")
        self.pushButton_2.setEnabled(True)
        self.pushButton_2.setText('restart')



    def auto(self):

        # 添加一个全局变量，来让线程1调用线程2
        self.autostatus = 1
        # 移动窗口至右上角
        desktop = QApplication.desktop()
        self.move(desktop.width() - self.width(), 0)

        self.pushButton_3.setEnabled(False)
        self.pushButton_3.setText('正在\n执行')
        self.pushButton_3.setStyleSheet("color: rgb(137, 221, 255);\n"
        "background-color: rgb(0,205,0,0.5);\n"
        "border-style:none;\n"
        "border:1px solid #3f3f3f; \n"
        "\n"
        "padding:5px;\n"
        "min-height:20px;\n"
        "border-radius:25px;")
        self.process1()



    def printf(self, mystr):

        self.textBrowser.append(mystr)  # 在指定的区域显示提示信息
        self.cursor = self.textBrowser.textCursor()
        self.textBrowser.moveCursor(self.cursor.End)  # 光标移到最后，这样就会自动显示出来
        QtWidgets.QApplication.processEvents()  # 一定加上这个功能，不然有卡顿

    def open_chrome(self):
        try:
            auto = self.autostatus
            print("创建一个新线程，并打开浏览器")
            self.printf('打开浏览器')
            self.pushButton_4.setText('Ongoing')
            self.pushButton_4.setStyleSheet("color: rgb(137, 221, 255);\n"
            "background-color: rgb(0,205,0,0.5);\n"
            "border-style:none;\n"
            "border:1px solid #3f3f3f; \n"
            "\n"
            "padding:5px;\n"
            "\n"
            "border-radius:8px;")
            mytread3 = Mythread3()
            mytread3.openchromesignal.connect(self.dyauto)
            mytread3.start()
            mytread3.exec()
        except AttributeError:
            print("创建一个新线程，并打开浏览器")
            self.printf('打开浏览器')
            self.pushButton_4.setText('Ongoing')
            self.pushButton_4.setStyleSheet("color: rgb(137, 221, 255);\n"
            "background-color: rgb(0,205,0,0.5);\n"
            "border-style:none;\n"
            "border:1px solid #3f3f3f; \n"
            "\n"
            "padding:5px;\n"
            "\n"
            "border-radius:8px;")
            mytread3 = Mythread3()
            mytread3.start()
            mytread3.exec()



    # 重写移动监听事件(用途拖动窗口位置)
    def mouseMoveEvent(self, e:   QtGui.QMouseEvent):  # 重写移动事件
        self._endPos = e.pos() - self._startPos
        self.move(self.pos() + self._endPos)

    def mousePressEvent(self, e: QtGui.QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._isTracking = True
            self._startPos = QPoint(e.x(), e.y())

    def mouseReleaseEvent(self, e: QtGui.QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._isTracking = False
            self._startPos = None
            self._endPos = None


class Mythread1(QThread):

    erpauto = pyqtSignal(str)
    erpbtnsignal = pyqtSignal()

    def __init__(self,excel_path, work_path):
        super(Mythread1, self).__init__()
        self.excel_path = excel_path
        self.work_path = work_path

    def run(self):
        excel_path = self.excel_path
        work_path = self.work_path
        goods_dict = {}
        data = xlrd.open_workbook(excel_path)
        table = data.sheets()[0]
        goods_list = table.col_values(0)
        print(goods_list)
        print('输入的工作路径', work_path)
        st = Erpauto(work_path)
        st.start()
        row = 1
        for goods in goods_list:
            self.erpauto.emit('{} 当前执行到{}行'.format(datetime.datetime.now(),row))
            good_info = st.read(goods)
            print('返回的列表为', good_info)
            goods_dict[goods] = good_info

            # goods_dict[goods] = goods
            # print('当前执行到{}行'.format(row))
            # ui.printf('{} 当前执行到{}行'.format(datetime.datetime.now(),row))
            # ui.printf('货号为{}'.format(goods))
            row += 1
        print(goods_dict)
        dict_path = os.path.join(work_path, 'goods_dict.txt')
        # dic=    goods_dict={'MA032405-2': ['MA032405-2', '套装-毛衣', ['花色'], ['S', 'M', 'L', 'XL']],
        #  'MQ032254': ['MQ032254', '连衣裙', ['黑色', '天蓝色'], ['XS', 'S', 'M', 'L', 'XL']],
        #  'MA032551-1': ['MA032551-1', '套装-衬衫', ['白色'], ['XS', 'S', 'M', 'L', 'XL']]}
        with open(dict_path, 'w+') as f:
            f.write(str(goods_dict))
            f.close()
        st.join()
        self.erpauto.emit('erp数据获取完成')
        self.erpbtnsignal.emit()




class Mythread2(QThread):

    chromesig = pyqtSignal(str)
    dybtnsignal = pyqtSignal()

    def __init__(self,chrome_driver,work_path):
        super(Mythread2, self).__init__()
        self.chrome_driver = chrome_driver
        self.work_path = work_path

    def run(self):
        print('开始chrome抖音小店自动上新')
        chrome_driver=self.chrome_driver
        work_path = self.work_path
        chrome_options = Options()
        chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9999")
        driver = webdriver.Chrome(chrome_driver, options=chrome_options)
        dyshop = DYSHOP(driver)
        dyshop.login()
        dict_path = os.path.join(work_path, 'goods_dict.txt')
        with open(dict_path, 'r+') as f:
            goods_dict = eval(f.read())
            f.close()
        # goods_dict = {'MA032405-2': ['MA032405-2', '套装-毛衣', ['花色'], ['S', 'M', 'L', 'XL']],
        #               'MQ032254': ['MQ032254', '连衣裙', ['黑色', '天蓝色'], ['XS', 'S', 'M', 'L', 'XL']],
        #               'MA032551-1': ['MA032551-1', '套装-衬衫', ['白色'], ['XS', 'S', 'M', 'L', 'XL']]}

        for good in goods_dict:
            good_log = '{} 正在上新货号为:{}'.format(datetime.datetime.now(), good)
            self.chromesig.emit(good_log)
            dyshop.create_goods(goods_dict[good])

        self.chromesig.emit('抖音小店上新执行完毕')
        self.dybtnsignal.emit()


class Mythread3(QThread):

    openchromesignal = pyqtSignal()

    def __init__(self):
        super(Mythread3,self).__init__()
    def run(self):

        openchromedef()
        self.openchromesignal.emit()


if __name__ == '__main__':
    app = QApplication(sys.argv)

    #定义QSplashScreen 插入启动页背景图
    splash = QSplashScreen(QtGui.QPixmap("./resource/loadbg1.jpg"))
    splash.show()
    #定义字体格式
    font = QtGui.QFont()
    font.setPointSize(10)
    # font.setBold(True)
    font.setWeight(75)
    splash.setFont(font)
    splash.showMessage("正在加载.....",Qt.AlignBottom|Qt.AlignRight,Qt.white,)
    time.sleep(1)
    splash.showMessage("正在渲染图片.....", Qt.AlignBottom|Qt.AlignRight, Qt.white)
    time.sleep(1)
    splash.showMessage("正在渲染样式.....", Qt.AlignBottom|Qt.AlignRight, Qt.white)
    time.sleep(1)
    # 设置进程，启动加载页面时可以进行其他操作而不会卡死
    app.processEvents()

    ui = Myapp()
    ui.show()
    # 结束启动页
    splash.finish(ui)
    sys.exit(app.exec_())
